package dev.ece.core.controller;

import java.util.Iterator;
import java.util.Vector;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ControllerGroup extends Vector<Controller> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3949858806771581453L;
	
	private final Logger log = LogManager.getLogger(ControllerGroup.class);
	
	private boolean valid = true;
	
	public synchronized void execute() {
		if(this.isValid()) {
			Iterator<Controller> it = this.iterator();
			Controller controller = null;
			while(it.hasNext()) {
				controller = it.next();
				if(controller.isValid()) {
					try {
						controller.execute();
					} catch(Exception e) {
						log.error("控制执行异常", e);
					}
					return;
				}
			}
		}
	}
	
	public synchronized void keyBoardEvent(int key, int action) {
		if(this.isValid()) {
			Iterator<Controller> it = this.iterator();
			Controller controller = null;
			while(it.hasNext()) {
				controller = it.next();
				if(controller.isValid()) {
					try {
						if(controller.keyBoardEvent(key, action)) {
							return;
						};
					} catch(Exception e) {
						log.error("控制按键事件异常", e);
					}
				}
			}
		}
	}

	public boolean isValid() {
		return valid;
	}

	public synchronized void setValid(boolean valid) {
		this.valid = valid;
		if(!valid) {
			Iterator<Controller> it = this.iterator();
			while(it.hasNext()) {
				it.next().stopCommands();
			}
		}
	}
	
}
